<!-- HTML header for doxygen 1.8.6-->
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.13"/>
<title>OpenCV: samples/cpp/squares.cpp</title>
<link href="../../opencv.ico" rel="shortcut icon" type="image/x-icon" />
<link href="../../tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="../../jquery.js"></script>
<script type="text/javascript" src="../../dynsections.js"></script>
<script type="text/javascript" src="../../tutorial-utils.js"></script>
<link href="../../search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="../../search/searchdata.js"></script>
<script type="text/javascript" src="../../search/search.js"></script>
<script type="text/x-mathjax-config">
  MathJax.Hub.Config({
    extensions: ["tex2jax.js", "TeX/AMSmath.js", "TeX/AMSsymbols.js"],
    jax: ["input/TeX","output/HTML-CSS"],
});
//<![CDATA[
MathJax.Hub.Config(
{
  TeX: {
      Macros: {
          matTT: [ "\\[ \\left|\\begin{array}{ccc} #1 & #2 & #3\\\\ #4 & #5 & #6\\\\ #7 & #8 & #9 \\end{array}\\right| \\]", 9],
          fork: ["\\left\\{ \\begin{array}{l l} #1 & \\mbox{#2}\\\\ #3 & \\mbox{#4}\\\\ \\end{array} \\right.", 4],
          forkthree: ["\\left\\{ \\begin{array}{l l} #1 & \\mbox{#2}\\\\ #3 & \\mbox{#4}\\\\ #5 & \\mbox{#6}\\\\ \\end{array} \\right.", 6],
          forkfour: ["\\left\\{ \\begin{array}{l l} #1 & \\mbox{#2}\\\\ #3 & \\mbox{#4}\\\\ #5 & \\mbox{#6}\\\\ #7 & \\mbox{#8}\\\\ \\end{array} \\right.", 8],
          vecthree: ["\\begin{bmatrix} #1\\\\ #2\\\\ #3 \\end{bmatrix}", 3],
          vecthreethree: ["\\begin{bmatrix} #1 & #2 & #3\\\\ #4 & #5 & #6\\\\ #7 & #8 & #9 \\end{bmatrix}", 9],
          cameramatrix: ["#1 = \\begin{bmatrix} f_x & 0 & c_x\\\\ 0 & f_y & c_y\\\\ 0 & 0 & 1 \\end{bmatrix}", 1],
          distcoeffs: ["(k_1, k_2, p_1, p_2[, k_3[, k_4, k_5, k_6 [, s_1, s_2, s_3, s_4[, \\tau_x, \\tau_y]]]]) \\text{ of 4, 5, 8, 12 or 14 elements}"],
          distcoeffsfisheye: ["(k_1, k_2, k_3, k_4)"],
          hdotsfor: ["\\dots", 1],
          mathbbm: ["\\mathbb{#1}", 1],
          bordermatrix: ["\\matrix{#1}", 1]
      }
  }
}
);
//]]>
</script><script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.0/MathJax.js"></script>
<link href="../../doxygen.css" rel="stylesheet" type="text/css" />
<link href="../../stylesheet.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<!--#include virtual="/google-search.html"-->
<table cellspacing="0" cellpadding="0">
 <tbody>
 <tr style="height: 56px;">
  <td id="projectlogo"><img alt="Logo" src="../../opencv-logo-small.png"/></td>
  <td style="padding-left: 0.5em;">
   <div id="projectname">OpenCV
   &#160;<span id="projectnumber">4.5.2</span>
   </div>
   <div id="projectbrief">Open Source Computer Vision</div>
  </td>
 </tr>
 </tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.8.13 -->
<script type="text/javascript">
var searchBox = new SearchBox("searchBox", "../../search",false,'Search');
</script>
<script type="text/javascript" src="../../menudata.js"></script>
<script type="text/javascript" src="../../menu.js"></script>
<script type="text/javascript">
$(function() {
  initMenu('../../',true,false,'search.php','Search');
  $(document).ready(function() { init_search(); });
});
</script>
<div id="main-nav"></div>
</div><!-- top -->
<!-- window showing the filter options -->
<div id="MSearchSelectWindow"
     onmouseover="return searchBox.OnSearchSelectShow()"
     onmouseout="return searchBox.OnSearchSelectHide()"
     onkeydown="return searchBox.OnSearchSelectKey(event)">
</div>

<!-- iframe showing the search results (closed by default) -->
<div id="MSearchResultsWindow">
<iframe src="javascript:void(0)" frameborder="0" 
        name="MSearchResults" id="MSearchResults">
</iframe>
</div>

<div class="header">
  <div class="headertitle">
<div class="title">samples/cpp/squares.cpp</div>  </div>
</div><!--header-->
<div class="contents">
<p>A program using pyramid scaling, Canny, contours and contour simplification to find squares in a list of images (pic1-6.png). Returns sequence of squares detected on the image.</p>
<div class="fragment"><div class="line"></div><div class="line"><span class="comment">// The &quot;Square Detector&quot; program.</span></div><div class="line"><span class="comment">// It loads several images sequentially and tries to find squares in</span></div><div class="line"><span class="comment">// each image</span></div><div class="line"></div><div class="line"><span class="preprocessor">#include &quot;<a class="code" href="../../d0/d9c/core_2include_2opencv2_2core_8hpp.html">opencv2/core.hpp</a>&quot;</span></div><div class="line"><span class="preprocessor">#include &quot;<a class="code" href="../../d1/d4f/imgproc_2include_2opencv2_2imgproc_8hpp.html">opencv2/imgproc.hpp</a>&quot;</span></div><div class="line"><span class="preprocessor">#include &quot;<a class="code" href="../../d6/d87/imgcodecs_8hpp.html">opencv2/imgcodecs.hpp</a>&quot;</span></div><div class="line"><span class="preprocessor">#include &quot;<a class="code" href="../../d4/dd5/highgui_8hpp.html">opencv2/highgui.hpp</a>&quot;</span></div><div class="line"></div><div class="line"><span class="preprocessor">#include &lt;iostream&gt;</span></div><div class="line"></div><div class="line"><span class="keyword">using namespace </span><a class="code" href="../../d2/d75/namespacecv.html">cv</a>;</div><div class="line"><span class="keyword">using namespace </span><a class="code" href="../../d8/dcc/namespacestd.html">std</a>;</div><div class="line"></div><div class="line"><span class="keyword">static</span> <span class="keywordtype">void</span> help(<span class="keyword">const</span> <span class="keywordtype">char</span>* programName)</div><div class="line">{</div><div class="line">    cout &lt;&lt;</div><div class="line">    <span class="stringliteral">&quot;\nA program using pyramid scaling, Canny, contours and contour simplification\n&quot;</span></div><div class="line">    <span class="stringliteral">&quot;to find squares in a list of images (pic1-6.png)\n&quot;</span></div><div class="line">    <span class="stringliteral">&quot;Returns sequence of squares detected on the image.\n&quot;</span></div><div class="line">    <span class="stringliteral">&quot;Call:\n&quot;</span></div><div class="line">    <span class="stringliteral">&quot;./&quot;</span> &lt;&lt; programName &lt;&lt; <span class="stringliteral">&quot; [file_name (optional)]\n&quot;</span></div><div class="line">    <span class="stringliteral">&quot;Using OpenCV version &quot;</span> &lt;&lt; <a name="a0"></a><a class="code" href="../../da/dd7/core_2include_2opencv2_2core_2version_8hpp.html#a4f050efda432e041621b3af3df140adc">CV_VERSION</a> &lt;&lt; <span class="stringliteral">&quot;\n&quot;</span> &lt;&lt; endl;</div><div class="line">}</div><div class="line"></div><div class="line"></div><div class="line"><span class="keywordtype">int</span> thresh = 50, N = 11;</div><div class="line"><span class="keyword">const</span> <span class="keywordtype">char</span>* wndname = <span class="stringliteral">&quot;Square Detection Demo&quot;</span>;</div><div class="line"></div><div class="line"><span class="comment">// helper function:</span></div><div class="line"><span class="comment">// finds a cosine of angle between vectors</span></div><div class="line"><span class="comment">// from pt0-&gt;pt1 and from pt0-&gt;pt2</span></div><div class="line"><span class="keyword">static</span> <span class="keywordtype">double</span> angle( <a name="_a1"></a><a class="code" href="../../db/d4e/classcv_1_1Point__.html">Point</a> pt1, <a class="code" href="../../db/d4e/classcv_1_1Point__.html">Point</a> pt2, <a class="code" href="../../db/d4e/classcv_1_1Point__.html">Point</a> pt0 )</div><div class="line">{</div><div class="line">    <span class="keywordtype">double</span> dx1 = pt1.<a name="a2"></a><a class="code" href="../../db/d4e/classcv_1_1Point__.html#a4c96fa7bdbfe390be5ed356edb274ff3">x</a> - pt0.<a class="code" href="../../db/d4e/classcv_1_1Point__.html#a4c96fa7bdbfe390be5ed356edb274ff3">x</a>;</div><div class="line">    <span class="keywordtype">double</span> dy1 = pt1.<a name="a3"></a><a class="code" href="../../db/d4e/classcv_1_1Point__.html#a157337197338ff199e5df1a393022f15">y</a> - pt0.<a class="code" href="../../db/d4e/classcv_1_1Point__.html#a157337197338ff199e5df1a393022f15">y</a>;</div><div class="line">    <span class="keywordtype">double</span> dx2 = pt2.<a class="code" href="../../db/d4e/classcv_1_1Point__.html#a4c96fa7bdbfe390be5ed356edb274ff3">x</a> - pt0.<a class="code" href="../../db/d4e/classcv_1_1Point__.html#a4c96fa7bdbfe390be5ed356edb274ff3">x</a>;</div><div class="line">    <span class="keywordtype">double</span> dy2 = pt2.<a class="code" href="../../db/d4e/classcv_1_1Point__.html#a157337197338ff199e5df1a393022f15">y</a> - pt0.<a class="code" href="../../db/d4e/classcv_1_1Point__.html#a157337197338ff199e5df1a393022f15">y</a>;</div><div class="line">    <span class="keywordflow">return</span> (dx1*dx2 + dy1*dy2)/<a name="a4"></a><a class="code" href="../../d0/de1/group__core.html#ga9070b6a3f093dd952d973819b06f4906">sqrt</a>((dx1*dx1 + dy1*dy1)*(dx2*dx2 + dy2*dy2) + 1e-10);</div><div class="line">}</div><div class="line"></div><div class="line"><span class="comment">// returns sequence of squares detected on the image.</span></div><div class="line"><span class="keyword">static</span> <span class="keywordtype">void</span> findSquares( <span class="keyword">const</span> <a name="_a5"></a><a class="code" href="../../d3/d63/classcv_1_1Mat.html">Mat</a>&amp; image, vector&lt;vector&lt;Point&gt; &gt;&amp; squares )</div><div class="line">{</div><div class="line">    squares.clear();</div><div class="line"></div><div class="line">    <a class="code" href="../../d3/d63/classcv_1_1Mat.html">Mat</a> pyr, timg, gray0(image.<a name="a6"></a><a class="code" href="../../d3/d63/classcv_1_1Mat.html#a146f8e8dda07d1365a575ab83d9828d1">size</a>(), <a name="a7"></a><a class="code" href="../../d1/d1b/group__core__hal__interface.html#ga32b18d904ee2b1731a9416a8eef67d06">CV_8U</a>), gray;</div><div class="line"></div><div class="line">    <span class="comment">// down-scale and upscale the image to filter out the noise</span></div><div class="line">    <a name="a8"></a><a class="code" href="../../d4/d86/group__imgproc__filter.html#gaf9bba239dfca11654cb7f50f889fc2ff">pyrDown</a>(image, pyr, <a name="a9"></a><a class="code" href="../../dc/d84/group__core__basic.html#ga346f563897249351a34549137c8532a0">Size</a>(image.<a name="a10"></a><a class="code" href="../../d3/d63/classcv_1_1Mat.html#aa3e5a47585c9ef6a0842556739155e3e">cols</a>/2, image.<a name="a11"></a><a class="code" href="../../d3/d63/classcv_1_1Mat.html#abed816466c45234254d25bc59c31245e">rows</a>/2));</div><div class="line">    <a name="a12"></a><a class="code" href="../../d4/d86/group__imgproc__filter.html#gada75b59bdaaca411ed6fee10085eb784">pyrUp</a>(pyr, timg, image.<a class="code" href="../../d3/d63/classcv_1_1Mat.html#a146f8e8dda07d1365a575ab83d9828d1">size</a>());</div><div class="line">    vector&lt;vector&lt;Point&gt; &gt; contours;</div><div class="line"></div><div class="line">    <span class="comment">// find squares in every color plane of the image</span></div><div class="line">    <span class="keywordflow">for</span>( <span class="keywordtype">int</span> c = 0; c &lt; 3; c++ )</div><div class="line">    {</div><div class="line">        <span class="keywordtype">int</span> ch[] = {c, 0};</div><div class="line">        <a name="a13"></a><a class="code" href="../../d2/de8/group__core__array.html#ga51d768c270a1cdd3497255017c4504be">mixChannels</a>(&amp;timg, 1, &amp;gray0, 1, ch, 1);</div><div class="line"></div><div class="line">        <span class="comment">// try several threshold levels</span></div><div class="line">        <span class="keywordflow">for</span>( <span class="keywordtype">int</span> l = 0; l &lt; N; l++ )</div><div class="line">        {</div><div class="line">            <span class="comment">// hack: use Canny instead of zero threshold level.</span></div><div class="line">            <span class="comment">// Canny helps to catch squares with gradient shading</span></div><div class="line">            <span class="keywordflow">if</span>( l == 0 )</div><div class="line">            {</div><div class="line">                <span class="comment">// apply Canny. Take the upper threshold from slider</span></div><div class="line">                <span class="comment">// and set the lower to 0 (which forces edges merging)</span></div><div class="line">                <a name="a14"></a><a class="code" href="../../dd/d1a/group__imgproc__feature.html#ga04723e007ed888ddf11d9ba04e2232de">Canny</a>(gray0, gray, 0, thresh, 5);</div><div class="line">                <span class="comment">// dilate canny output to remove potential</span></div><div class="line">                <span class="comment">// holes between edge segments</span></div><div class="line">                <a name="a15"></a><a class="code" href="../../d4/d86/group__imgproc__filter.html#ga4ff0f3318642c4f469d0e11f242f3b6c">dilate</a>(gray, gray, <a class="code" href="../../d3/d63/classcv_1_1Mat.html">Mat</a>(), <a name="a16"></a><a class="code" href="../../dc/d84/group__core__basic.html#ga1e83eafb2d26b3c93f09e8338bcab192">Point</a>(-1,-1));</div><div class="line">            }</div><div class="line">            <span class="keywordflow">else</span></div><div class="line">            {</div><div class="line">                <span class="comment">// apply threshold if l!=0:</span></div><div class="line">                <span class="comment">//     tgray(x,y) = gray(x,y) &lt; (l+1)*255/N ? 255 : 0</span></div><div class="line">                gray = gray0 &gt;= (l+1)*255/N;</div><div class="line">            }</div><div class="line"></div><div class="line">            <span class="comment">// find contours and store them all as a list</span></div><div class="line">            <a name="a17"></a><a class="code" href="../../d3/dc0/group__imgproc__shape.html#gadf1ad6a0b82947fa1fe3c3d497f260e0">findContours</a>(gray, contours, <a name="a18"></a><a class="code" href="../../d3/dc0/group__imgproc__shape.html#gga819779b9857cc2f8601e6526a3a5bc71a48b9c2cb1056f775ae50bb68288b875e">RETR_LIST</a>, <a name="a19"></a><a class="code" href="../../d3/dc0/group__imgproc__shape.html#gga4303f45752694956374734a03c54d5ffa5f2883048e654999209f88ba04c302f5">CHAIN_APPROX_SIMPLE</a>);</div><div class="line"></div><div class="line">            vector&lt;Point&gt; approx;</div><div class="line"></div><div class="line">            <span class="comment">// test each contour</span></div><div class="line">            <span class="keywordflow">for</span>( <span class="keywordtype">size_t</span> i = 0; i &lt; contours.size(); i++ )</div><div class="line">            {</div><div class="line">                <span class="comment">// approximate contour with accuracy proportional</span></div><div class="line">                <span class="comment">// to the contour perimeter</span></div><div class="line">                <a name="a20"></a><a class="code" href="../../d3/dc0/group__imgproc__shape.html#ga0012a5fdaea70b8a9970165d98722b4c">approxPolyDP</a>(contours[i], approx, <a name="a21"></a><a class="code" href="../../d3/dc0/group__imgproc__shape.html#ga8d26483c636be6b35c3ec6335798a47c">arcLength</a>(contours[i], <span class="keyword">true</span>)*0.02, <span class="keyword">true</span>);</div><div class="line"></div><div class="line">                <span class="comment">// square contours should have 4 vertices after approximation</span></div><div class="line">                <span class="comment">// relatively large area (to filter out noisy contours)</span></div><div class="line">                <span class="comment">// and be convex.</span></div><div class="line">                <span class="comment">// Note: absolute value of an area is used because</span></div><div class="line">                <span class="comment">// area may be positive or negative - in accordance with the</span></div><div class="line">                <span class="comment">// contour orientation</span></div><div class="line">                <span class="keywordflow">if</span>( approx.size() == 4 &amp;&amp;</div><div class="line">                    fabs(<a name="a22"></a><a class="code" href="../../d3/dc0/group__imgproc__shape.html#ga2c759ed9f497d4a618048a2f56dc97f1">contourArea</a>(approx)) &gt; 1000 &amp;&amp;</div><div class="line">                    <a name="a23"></a><a class="code" href="../../d3/dc0/group__imgproc__shape.html#ga8abf8010377b58cbc16db6734d92941b">isContourConvex</a>(approx) )</div><div class="line">                {</div><div class="line">                    <span class="keywordtype">double</span> maxCosine = 0;</div><div class="line"></div><div class="line">                    <span class="keywordflow">for</span>( <span class="keywordtype">int</span> j = 2; j &lt; 5; j++ )</div><div class="line">                    {</div><div class="line">                        <span class="comment">// find the maximum cosine of the angle between joint edges</span></div><div class="line">                        <span class="keywordtype">double</span> cosine = fabs(angle(approx[j%4], approx[j-2], approx[j-1]));</div><div class="line">                        maxCosine = <a name="a24"></a><a class="code" href="../../db/de0/group__core__utils.html#gafa99ec4acc4ecb2dc3c2d05da15d0e3f">MAX</a>(maxCosine, cosine);</div><div class="line">                    }</div><div class="line"></div><div class="line">                    <span class="comment">// if cosines of all angles are small</span></div><div class="line">                    <span class="comment">// (all angles are ~90 degree) then write quandrange</span></div><div class="line">                    <span class="comment">// vertices to resultant sequence</span></div><div class="line">                    <span class="keywordflow">if</span>( maxCosine &lt; 0.3 )</div><div class="line">                        squares.push_back(approx);</div><div class="line">                }</div><div class="line">            }</div><div class="line">        }</div><div class="line">    }</div><div class="line">}</div><div class="line"></div><div class="line"><span class="keywordtype">int</span> main(<span class="keywordtype">int</span> argc, <span class="keywordtype">char</span>** argv)</div><div class="line">{</div><div class="line">    <span class="keyword">static</span> <span class="keyword">const</span> <span class="keywordtype">char</span>* names[] = { <span class="stringliteral">&quot;pic1.png&quot;</span>, <span class="stringliteral">&quot;pic2.png&quot;</span>, <span class="stringliteral">&quot;pic3.png&quot;</span>,</div><div class="line">        <span class="stringliteral">&quot;pic4.png&quot;</span>, <span class="stringliteral">&quot;pic5.png&quot;</span>, <span class="stringliteral">&quot;pic6.png&quot;</span>, 0 };</div><div class="line">    help(argv[0]);</div><div class="line"></div><div class="line">    <span class="keywordflow">if</span>( argc &gt; 1)</div><div class="line">    {</div><div class="line">     names[0] =  argv[1];</div><div class="line">     names[1] =  <span class="stringliteral">&quot;0&quot;</span>;</div><div class="line">    }</div><div class="line"></div><div class="line">    <span class="keywordflow">for</span>( <span class="keywordtype">int</span> i = 0; names[i] != 0; i++ )</div><div class="line">    {</div><div class="line">        <span class="keywordtype">string</span> filename = <a name="a25"></a><a class="code" href="../../d6/dba/group__core__utils__samples.html#ga3a33b00033b46c698ff6340d95569c13">samples::findFile</a>(names[i]);</div><div class="line">        <a class="code" href="../../d3/d63/classcv_1_1Mat.html">Mat</a> image = <a name="a26"></a><a class="code" href="../../d4/da8/group__imgcodecs.html#ga288b8b3da0892bd651fce07b3bbd3a56">imread</a>(filename, <a name="a27"></a><a class="code" href="../../d8/d6a/group__imgcodecs__flags.html#gga61d9b0126a3e57d9277ac48327799c80af660544735200cbe942eea09232eb822">IMREAD_COLOR</a>);</div><div class="line">        <span class="keywordflow">if</span>( image.<a name="a28"></a><a class="code" href="../../d3/d63/classcv_1_1Mat.html#abbec3525a852e77998aba034813fded4">empty</a>() )</div><div class="line">        {</div><div class="line">            cout &lt;&lt; <span class="stringliteral">&quot;Couldn&#39;t load &quot;</span> &lt;&lt; filename &lt;&lt; endl;</div><div class="line">            <span class="keywordflow">continue</span>;</div><div class="line">        }</div><div class="line"></div><div class="line">        vector&lt;vector&lt;Point&gt; &gt; squares;</div><div class="line">        findSquares(image, squares);</div><div class="line"></div><div class="line">        <a name="a29"></a><a class="code" href="../../d6/d6e/group__imgproc__draw.html#ga1ea127ffbbb7e0bfc4fd6fd2eb64263c">polylines</a>(image, squares, <span class="keyword">true</span>, <a name="a30"></a><a class="code" href="../../dc/d84/group__core__basic.html#ga599fe92e910c027be274233eccad7beb">Scalar</a>(0, 255, 0), 3, <a name="a31"></a><a class="code" href="../../d6/d6e/group__imgproc__draw.html#ggaf076ef45de481ac96e0ab3dc2c29a777a85fdabe5335c9e6656563dfd7c94fb4f">LINE_AA</a>);</div><div class="line">        <a name="a32"></a><a class="code" href="../../d7/dfc/group__highgui.html#ga453d42fe4cb60e5723281a89973ee563">imshow</a>(wndname, image);</div><div class="line"></div><div class="line">        <span class="keywordtype">int</span> c = <a name="a33"></a><a class="code" href="../../d7/dfc/group__highgui.html#ga5628525ad33f52eab17feebcfba38bd7">waitKey</a>();</div><div class="line">        <span class="keywordflow">if</span>( c == 27 )</div><div class="line">            <span class="keywordflow">break</span>;</div><div class="line">    }</div><div class="line"></div><div class="line">    <span class="keywordflow">return</span> 0;</div><div class="line">}</div></div><!-- fragment --> </div><!-- contents -->
<!-- HTML footer for doxygen 1.8.6-->
<!-- start footer part -->
<hr class="footer"/><address class="footer"><small>
Generated on Fri Apr 2 2021 11:36:29 for OpenCV by &#160;<a href="http://www.doxygen.org/index.html">
<img class="footer" src="../../doxygen.png" alt="doxygen"/>
</a> 1.8.13
</small></address>
<script type="text/javascript">
//<![CDATA[
addTutorialsButtons();
//]]>
</script>
</body>
</html>
